$(function () {
    let screenPublicationId = null;

    var isAppoint = false;

    let answerResult = {};

    var isCheckin = false;

    var isLogin = false;

    var isReady = false;

    var backendUrl = '';

    var initData = {};

    var getStatsIntervalId = 0; //推流监控定时器id

    //访客呼叫的分组
    var customerService = 1;

    //振铃呼入数据
    var incomingCallData = {};

    var streamAddEvent,
        streamEndEvent,
        agentJoinSessionEvent,
        agentQuitSessionEvent,
        customerJoinSessionEvent,
        customerQuitSessionEvent;

    $('#mic').on('click', function () {
        ivcs.agent.microphoneTest(
            (resp) => {
                console.log('success', resp);
            },
            (error) => {
                console.log('error', error);
            }
        );
    });

    $('#camera').on('click', function () {
        ivcs.agent.cameraTest(
            null,
            (resp) => {
                console.log('success', resp);
            },
            (error) => {
                console.log('error', error);
            }
        );
    });

    $('#init').on('click', function () {
        let testName = document.getElementById('name').value;
        let testPwd = document.getElementById('pwd').value;
        let testOrg = document.getElementById('org').value;
        backendUrl = document.getElementById('backend_url_id').value;
        ivcs.agent.init(
            backendUrl,
            testName,
            testPwd,
            testOrg,
            undefined,
            function (resp) {
                console.log(resp, ivcs);
                initData = resp;
                setCurrentState('初始化成功');
                showButton('ivcs_agent_login,joinsession');
                setGroups(resp.groupsList);
            },
            function (error) {
                console.log('init error', error);
                if (error && error.data && error.data.message) {
                    alert(error.data.message);
                }
            }
        );
    });

    function setGroups(groups) {
        var obj = document.getElementById('groupSelect');
        groups.forEach((item) => {
            obj.options.add(new Option(item.name, item._id));
        });
    }

    /**
     * 强插会话
     */
    $('#joinsession').on('click', function () {
        let sessionId = document.getElementById('sessionId').value;
        if (!sessionId) {
            alert('请输入插入的sessionId');
            return;
        }
        let testName = document.getElementById('name').value;
        let videoLabel = 'agent' + testName + Math.ceil(Math.random() * 10);
        ivcs.agent.joinSession(
            videoLabel,
            undefined,
            initData.token,
            backendUrl,
            sessionId,
            function (resp) {
                console.log('joinsession success', resp);
                joinSessionSuccess(resp);
            },
            function (error) {
                console.log('join session error', error);
                if (error && error.data && error.data.message) {
                    alert(error.data.message);
                }
            }
        );
    });

    $('#ivcs_agent_login').on('click', function () {
        ivcs.agent.login(
            (success) => {
                console.log('login success', success);
                setCurrentState('登入成功');
                isLogin = true;
                showButton('ivcs_agent_logout,agent_ready,checkin');
                ivcs.agent.onDrop(function (resp) {
                    console.log('on drop resp,', resp);
                    setCurrentState('drop');
                    showButton('init');
                });
                ivcs.agent.onRing(function (data) {
                    console.log('ring data', data);
                    setCurrentState('振铃中');
                    showButton('agent_answer,agent_reject');
                    incomingCallData = data;
                    customerService = data.userData.service;
                    let callMediaType =
                        incomingCallData &&
                        incomingCallData.userData &&
                        incomingCallData.userData.callMediaType
                            ? incomingCallData.userData.callMediaType
                            : 'video';
                    console.log('访客的呼叫媒体类型是', callMediaType);
                });
                ivcs.agent.onCancelRing(function (data) {
                    setCurrentState('振铃取消');
                    showButton('agent_unready');
                });
                ivcs.agent.addEventListener('systemError', (error) => {
                    console.log('system error', error);
                });
            },
            function (error) {
                console.log('login error', error);
            }
        );
    });

    $('#ivcs_agent_logout').on('click', function () {
        ivcs.agent.logout(
            function (resp) {
                console.log('logout success', resp);
                setCurrentState('已登出，');
                isLogin = false;
                showButton('init');
            },
            function (error) {
                console.log('logout error', error);
            }
        );
    });

    $('#checkin').on('click', function () {
        let groups = document.getElementById('groupSelect').value;
        if (groups === undefined || groups == null || groups === '') {
            alert('请输入坐席签入的分组groups');
            return;
        }
        let para = {
            groups: [parseInt(groups)],
        };
        console.log('checkin ,', para);
        ivcs.agent.checkIn(
            para,
            (resp) => {
                console.log('checkin success', resp);
                setCurrentState('已签入，');
                isCheckin = true;
                if (isReady) {
                    showButton('checkout,agent_unready,otherwork');
                } else {
                    showButton('checkout,agent_ready');
                }
            },
            (error) => {
                console.log('checkin error', error);
            }
        );
    });

    $('#checkout').on('click', function () {
        let groups = document.getElementById('groupSelect').value;
        if (groups === undefined || groups == null || groups === '') {
            alert('请输入坐席签出的分组groups');
            return;
        }
        let para = {
            groups: [parseInt(groups)],
        };
        console.log('checkout ,', para);
        ivcs.agent.checkOut(
            para,
            (resp) => {
                console.log('checkOut success', resp);
                setCurrentState('已签出，');
                isCheckin = false;
                if (isReady) {
                    showButton('checkin,agent_unready,otherwork');
                } else {
                    showButton('checkin,agent_ready');
                }
            },
            (error) => {
                console.log('checkOut error', error);
            }
        );
    });

    $('#agent_ready').on('click', function () {
        ivcs.agent.ready(
            function (status, resp) {
                console.log(status, resp);
                isAppoint = false;
                isReady = true;
                setCurrentState('就绪中');
                if (isCheckin) {
                    showButton(
                        'agent_unready,ivcs_agent_logout,checkout,otherwork'
                    );
                } else {
                    showButton(
                        'agent_unready,ivcs_agent_logout,checkin,otherwork'
                    );
                }
            },
            function (reason) {
                console.log(reason);
            }
        );
    });

    $('#agent_unready').on('click', function () {
        ivcs.agent.unReady(
            function (status, resp) {
                console.log(status, resp);
                isReady = false;
                setCurrentState('未就绪');
                if (isCheckin) {
                    showButton('agent_ready,ivcs_agent_logout,checkout');
                } else {
                    showButton('agent_ready,ivcs_agent_logout,checkin');
                }
            },
            function (reason) {
                console.log(reason);
            }
        );
    });

    $('#otherwork').on('click', function () {
        ivcs.agent.otherWork(
            'have a rest',
            function (resp) {
                console.log('otherWork success,', resp);
                setCurrentState('小休中');
                showButton('agent_ready,ivcs_agent_logout,checkin');
            },
            function (error) {
                console.log('otherWork error', error);
            }
        );
    });

    //踢人
    $('#dropClient').on('click', function () {
        let client_id = document.getElementById('client_id').value;
        if (!client_id) {
            alert('请输入clientId');
            return;
        }
        ivcs.agent.dropClient(
            client_id,
            function (status, resp) {
                console.log('drop client result', status, resp);
            },
            function (reason) {
                console.log(reason);
            }
        );
    });

    //会话中支持预约。
    $('#appoint_btn').on('click', function () {
        let obj = document.getElementById('appoint_state');
        var index = obj.selectedIndex; // 选中索引
        var value = obj.options[index].value; // 选中值
        console.log(index, value);
        let data = {
            appointState: value,
            reason: '整理内容',
        };
        ivcs.agent.appoint(
            data,
            (resp) => {
                console.log('appoint success', resp);
                isAppoint = true;
                setCurrentState('预约:' + data.reason);
                showButton(
                    'ivcs_agent_logout,agent_ready,checkin,agent_hanup,screenshare,handsign,transfer,three,dropClient,mute,unmute,photoguide,sed_btn,sendform,shareresource'
                );
            },
            (error) => {
                console.log('appoint error', error);
            }
        );
    });

    $('#agent_answer').on('click', function () {
        let testName = document.getElementById('name').value;
        let mediaType =
            incomingCallData &&
            incomingCallData.userData &&
            incomingCallData.userData.receiveMedia
                ? incomingCallData.userData.receiveMedia
                : 'video';
        ivcs.agent.answer(
            'agent' + testName,
            mediaType,
            undefined,
            (info) => {
                console.log('answer success', info);
                joinSessionSuccess(info);
            },
            (error) => {
                console.log(error);
                hangup();
            }
        );
    });

    $('#sendCancelInstructionMessage').on('click', function () {
        ivcs.agent.sendCancelInstructionMessage(
            'requset-location',
            'customers',
            (s) => {
                console.log('sendCancelInstructionMessage success', s);
            },
            (e) => {
                console.log('sendCancelInstructionMessage error', e);
            }
        );
    });

    $('#request_location').on('click', function () {
        ivcs.agent.requestLocation(
            {},
            'customers',
            (info) => {
                console.log('requestLocation success', info);
            },
            (error) => {
                console.log('requestLocation error', error);
            }
        );
    });

    $('#scan_code').on('click', function () {
        ivcs.agent.scanCode(
            {
                timeout: 1,
            },
            'customers',
            (info) => {
                console.log('scancode success', info);
            },
            (error) => {
                console.log('scancode error', error);
            }
        );
    });

    /**
     * 语音升级成视频通话
     */
    $('#audio-video').on('click', function () {
        ivcs.agent.voiceToVideo(
            (resp) => {
                console.log('voice to video success', resp);
            },
            (error) => {
                console.log('voice to video error', error);
            }
        );
    });

    /**
     * 加入通话成功
     * @param {*} info
     */
    function joinSessionSuccess(info) {
        answerResult = info;
        $('#sessionId').html('sessionId=' + info.sessionId);
        setCurrentState('通话中');
        showButton(
            'getstats,stopgetstats,agent_hanup,snapshot,screenshare,handsign,sendCancelInstructionMessage,transfer,three,dropClient,mute,photoguide,sed_btn,sendform,shareresource,appoint_btn,audio-video,request_location,scan_code'
        );
        streamAddEvent = ivcs.agent.addEventListener(
            'onStreamAdd',
            (streamInfo) => {
                console.log(streamInfo);
                var label = streamInfo.data.streamLabel;
                addVideoView(label);
                ivcs.agent.renderStream(
                    label,
                    label,
                    (resp) => {
                        console.log('render success', resp);
                    },
                    (error) => {
                        console.log('render error', error);
                    }
                );
            },
            (error) => {
                console.log('answer error', error);
            }
        );

        streamEndEvent = ivcs.agent.addEventListener(
            'onStreamEnd',
            (streamInfo) => {
                console.log('stream end', streamInfo);
            }
        );

        sessionParticipantEvent();

        ivcs.agent.onSessionDrop((resp) => {
            console.log('session drop,ccs drop', resp);
            hangup();
        });

        ivcs.agent.onTextMessage(function (data) {
            console.log('receive message', data);
            $('#message_list').append(
                $('<li>').text(`${JSON.stringify(data)}`)
            );
        });

        ivcs.agent.onResourceMessage(function (data) {
            console.log('receive resource message,,', data);
            $('#message_list').append(
                $('<li>').text(`${JSON.stringify(data)}`)
            );
        });

        // ivcs.agent.onHandSignature((data)=>{
        //   console.log('receive hand sign data',data);
        //   alert(data.data);
        // });
        //接收自定义消息
        ivcs.agent.onCustomMessage((message) => {
            console.log('receive custom message:', message);
        });
    }

    function sessionParticipantEvent() {
        customerJoinSessionEvent = ivcs.agent.addEventListener(
            'onCustomerJoinSession',
            (info) => {
                console.log('onCustomerJoinSession', info);
            }
        );

        agentQuitSessionEvent = ivcs.agent.addEventListener(
            'onAgentQuitSession',
            (info) => {
                console.log('onAgentQuitSession', info);
            }
        );

        customerQuitSessionEvent = ivcs.agent.addEventListener(
            'onCustomerQuitSession',
            (info) => {
                console.log('onCustomerQuitSession', info);
                setCurrentState('访客已离开');
                hangup();
            }
        );

        agentJoinSessionEvent = ivcs.agent.addEventListener(
            'onAgentJoinSession',
            (info) => {
                console.log('onAgentJoinSession', info);
            }
        );
    }

    function hangup() {
        ivcs.agent.hangup(
            {
                reason: '坐席挂断',
            },
            function (resp) {
                console.log('hangUp success', resp);
                setCurrentState('已挂断');
            },
            function (error) {
                console.log('hangUp error', error);
                setCurrentState('挂断失败，请刷新页面重新初始化并登入');
            }
        );
        if (isAppoint) {
            showButton('agent_ready,ivcs_agent_logout,checkin');
        } else {
            showButton('agent_unready,ivcs_agent_logout,checkin');
        }
        // ivcs.agent.removeEventListener('onStreamAdd', streamAddEvent);
        ivcs.agent.removeEventListener('onStreamEnd', streamEndEvent);
        ivcs.agent.removeEventListener(
            'onCustomerJoinSession',
            customerJoinSessionEvent
        );
        ivcs.agent.removeEventListener(
            'onAgentQuitSession',
            agentQuitSessionEvent
        );
        ivcs.agent.removeEventListener(
            'onCustomerQuitSession',
            customerQuitSessionEvent
        );
        ivcs.agent.removeEventListener(
            'onAgentJoinSession',
            agentJoinSessionEvent
        );
        removeAllVideoView();
    }

    $('#agent_reject').on('click', function () {
        ivcs.agent.reject(
            function (resp) {
                console.log('reject success', resp);
            },
            function (error) {
                console.log('reject error', error);
            }
        );
    });

    $('#agent_hanup').on('click', function () {
        hangup();
    });

    $('#screenshare').on('click', function () {
        ivcs.agent.screenShare(
            function (resp) {
                console.log('screenShare success', resp);
                screenPublicationId = resp;
                showButton(
                    'agent_hanup,stopscreenshare,handsign,transfer,three,dropClient,mute,photoguide,sed_btn,sendform,shareresource,audio-video'
                );
            },
            function (error) {
                console.log('screenShare error', error);
            },
            function (stop) {
                console.log('screen share stop', stop);
            },
            'testScreen'
        );
    });

    $('#stopscreenshare').on('click', function () {
        console.log('stop screen id', screenPublicationId);
        ivcs.agent.stopScreenShare(
            screenPublicationId,
            function (resp) {
                console.log('stopscreenshare success', resp);
                showButton(
                    'agent_hanup,screenshare,handsign,transfer,three,dropClient,mute,unmute,photoguide,sed_btn,sendform,shareresource,audio-video'
                );
            },
            function (error) {
                console.log('stopscreenshare error', error);
            }
        );
    });

    $('#transfer').on('click', function () {
        let agentId = $('#agentId').val();
        let data = {
            service: customerService,
            agentId: agentId,
        };
        ivcs.agent.transfer(
            data,
            true,
            function (resp) {
                console.log(resp);
            },
            function (error) {
                console.log(error);
            }
        );
    });

    $('#three').on('click', function () {
        let agentId = $('#agentId').val();
        let data = {
            service: customerService,
            agentId: agentId,
        };
        ivcs.agent.inviteOther(
            data,
            function (resp) {
                console.log(resp);
                showButton(
                    'agent_hanup,screenshare,handsign,transfer,three,dropClient,mute,unmute,photoguide,sed_btn,sendform,shareresource,audio-video'
                );
            },
            function (error) {
                console.log(error);
            }
        );
    });

    $('#mute').on('click', function () {
        ivcs.agent.mute(
            'audio',
            function () {
                console.log('mute audio succss');
                showButton(
                    'agent_hanup,screenshare,handsign,transfer,three,dropClient,unmute,photoguide,sed_btn,sendform,shareresource,audio-video'
                );
            },
            function (error) {
                console.log('mute audio failed', error);
            }
        );
    });

    $('#unmute').on('click', function () {
        ivcs.agent.unmute(
            'audio',
            function () {
                console.log('unmute audio succss');
                showButton(
                    'agent_hanup,screenshare,handsign,transfer,three,dropClient,mute,photoguide,sed_btn,sendform,shareresource,audio-video'
                );
            },
            function (error) {
                console.log('unmute audio failed', error);
            }
        );
    });

    $('#photoguide').on('click', function () {
        ivcs.agent.photoGuideBox(
            function () {
                console.log('photoGuideBox succss');
            },
            function (error) {
                console.log('photoGuideBox failed', error);
            }
        );
    });

    $('#handsign').on('click', function () {
        ivcs.agent.requestHandSignature(
            function () {
                console.log('invite hand sign succss');
            },
            function (error) {
                console.log('invite hand sign failed', error);
            }
        );
    });

    $('#sed_btn').on('click', function () {
        let msg = $('#msg_id').val();
        if (!msg) {
            console.log('place inout msg!');
            return;
        }
        ivcs.agent.sendTextMessage(
            msg,
            undefined,
            function (resp) {
                console.log('send success');
            },
            function (error) {
                console.log('send error', error);
            }
        );

        //发送自定义消息
        ivcs.agent.sendCustomMessage(
            'custom test message from agent' + msg,
            undefined,
            (resp) => {
                console.log('send custom success', resp);
            },
            (error) => {
                console.log(error);
            }
        );
    });

    $('#sendform').on('click', function () {
        let formData = {
            inputform: 1,
            formTemplate: answerResult.formTemplates[0],
        };
        console.log('form template', formData);
        ivcs.agent.sendForm(
            formData,
            undefined,
            function (resp) {
                console.log('send form success');
            },
            function (error) {
                console.log('send form error', error);
            }
        );
    });

    $('#shareresource').on('click', function () {
        var file = document.getElementById('input').files[0];
        var formData = new FormData();
        formData.append('file', file);
        ivcs.agent.shareResource(
            'doc',
            formData,
            undefined,
            function (resp) {
                console.log('share resource success', resp);
            },
            function (error) {
                console.log('share resource failed', error);
            }
        );
    });

    $('#snapshot').on('click', function () {
        ivcs.agent.requestScreenSnapshot(
            (resp) => {
                console.log('requestScreenSnapshot success', resp);
            },
            (error) => {
                console.log('requestScreenSnapshot failed', error);
            }
        );
    });
    //获取网络数据
    $('#getstats').on('click', function () {
        getStatsIntervalId = ivcs.agent.getLocalStreamStats(
            3000,
            (resp) => {
                console.log(
                    'get getLocalStreamStats,success',
                    resp,
                    new Date()
                );
            },
            (error) => {
                console.log('get getLocalStreamStats,failed', error);
            }
        );
    });

    //停止获取自己推流的网络数据
    $('#stopgetstats').on('click', function () {
        ivcs.agent.stopLocalStreamStats(
            getStatsIntervalId,
            (resp) => {
                console.log('stopLocalStreamStats,success', resp, new Date());
            },
            (error) => {
                console.log('stopLocalStreamStats,failed', error);
            }
        );
    });

    function showButton(ids) {
        let shows = ids.split(',');
        $('button').each(function () {
            if ($.inArray($(this).attr('id'), shows) >= 0) {
                $(this).attr('disabled', false);
            } else {
                $(this).attr('disabled', true);
            }
        });
    }
    function setCurrentState(state) {
        $('#agent-status').html(state);
    }
    function addVideoView(id) {
        var videoView = document.createElement('VIDEO');
        videoView.setAttribute('width', '320');
        videoView.setAttribute('height', '240');
        videoView.setAttribute('controls', 'controls');
        videoView.setAttribute('muted', 'muted');
        videoView.setAttribute('id', id);
        videoView.setAttribute('autoplay', 'autoplay');
        document.body.appendChild(videoView);
    }

    function removeAllVideoView() {
        var tagElements = document.getElementsByTagName('VIDEO');
        let length = tagElements.length;
        for (let m = 0; m < length; m++) {
            console.log(tagElements);
            tagElements[0].parentNode.removeChild(tagElements[0]);
        }
    }
});
